package com.DosonLeung.homeschoolcommunication.Utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.InputStream;
import java.net.URL;

/**
 * Created by DosonLeung on 2014/11/9.
 */
public class NetWorkUtil {

    private static HttpClient httpClient;
    private static int timeoutConnection = 60000;
    private static int timeoutSocket = 60000;

    //获取网络状态
    public static boolean getAvailableNetWorkInfo(Activity activity) {
        ConnectivityManager connectivityManager = (ConnectivityManager) activity
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        /* check network status */
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        /* check network status if it is available */
        if (activeNetInfo != null && activeNetInfo.isAvailable())
            return true;
        else
            return true;
    }

    //httpGet请求类
    public synchronized static String httpGet(String url) throws Exception {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);
        HttpConnectionParams.setSoTimeout(params, timeoutSocket);
        httpClient = new DefaultHttpClient(params);
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String responseString = EntityUtils.toString(httpResponse.getEntity());
                JSONTokener jsonTokener = new JSONTokener(responseString);
                JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
                if (jsonObject.get("status").toString().equalsIgnoreCase("200")) {
                    return jsonObject.getString("data");
                } else {
                    return jsonObject.getString("msg");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //返回详细信息的请求类
    public synchronized static JSONObject httpGetVerbose(String url) throws Exception {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);
        HttpConnectionParams.setSoTimeout(params, timeoutSocket);
        httpClient = new DefaultHttpClient(params);
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String responseString = EntityUtils.toString(httpResponse.getEntity());
                JSONTokener jsonTokener = new JSONTokener(responseString);
                JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
                return jsonObject;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //后台下载进程
    public static void startloaImageThread(String url,String quality){
        final String imageName = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")) + ".png";
        final String link = url + "?imageMogr2/quality/"+quality;
        new Thread() {
            public void run() {
                try {
                    Bitmap bitmap;
                    URL url = new URL(link);
                    InputStream is = url.openStream();
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = false;
                    int imageHeight = options.outHeight;
                    int imageWidth = options.outWidth;
                    int s = imageHeight * imageWidth;
                    if(s>10000){
                        options.inSampleSize = s/10;
                    }else {
                        options.inSampleSize = 2;
                    }
                    try {
                        bitmap = BitmapFactory.decodeStream(is,null,options);
                        StorageUtil.saveAsImage(imageName, bitmap);
                    }catch (OutOfMemoryError e){
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
